package website.haicheng.server.util;

import cn.hutool.json.JSONUtil;
import website.haicheng.server.model.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.CorruptedFrameException;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @Author: 582895699@qq.com
 * @Desctription: 解码
 * @Date: Created in 2021/12/1 15:44
 */
@Slf4j
public class MessageDecode extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> list) throws Exception {
        // 标记当前读取位置
        in.markReaderIndex();
        // 判断是否能够读取 length 长度
        if (in.readableBytes() <= 4) {
            return;
        }
        // 读取长度
        int length = in.readInt();
        if (length < 0) {
            throw new CorruptedFrameException("negative length: " + length);
        }
        // 如果 message 不够可读，则退回到原读取位置
        if (in.readableBytes() < length) {
            in.resetReaderIndex();
            return;
        }
        // 读取内容
        byte[] content = new byte[length];
        in.readBytes(content);

        Message nettyMessage = JSONUtil.toBean(new String(content), Message.class);
        list.add(nettyMessage);
        log.info("[decode][连接({}) 解析到一条消息({})]", channelHandlerContext.channel().id(), JSONUtil.toJsonStr(nettyMessage));
    }
}
